package com.dengyin2000.javaeye.ordering.action;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;

import com.dengyin2000.javaeye.ordering.entity.Dish;
import com.dengyin2000.javaeye.ordering.entity.DishOrder;

@Name("orderListAdminAction")
public class OrderListAdminAction implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4773729152046625540L;
	
	private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd");	
	
	@In("orderingDatabase")
	private Session session;
	
	private List<Dish> todayOrders;

	public List<Dish> getTodayOrders(){
		if (todayOrders == null) {
			 
			Date now = new Date();
			Calendar instance = Calendar.getInstance();
			instance.setTime(now);
			instance.add(Calendar.DAY_OF_MONTH, 1);
			Date tomorrow = instance.getTime();
			Query query = session.createQuery("select distinct o from DishOrder o left join fetch o.dishes where o.createDate>=:startDate and o.createDate<:endDate order by o.user");
			try {
				query.setDate("startDate", FORMAT.parse(FORMAT.format(now)));
				query.setDate("endDate", FORMAT.parse(FORMAT.format(tomorrow)));
			} catch (ParseException e) {
				query.setDate("startDate", now);
				query.setDate("endDate", tomorrow);
			}
			
			todayOrders = query.list();
		
		}
		return todayOrders;
	}

	public void setTodayOrders(List<Dish> todayOrders) {
		this.todayOrders = todayOrders;
	}
	
	public String getDishNoList(DishOrder order) {
		StringBuilder sb = new StringBuilder();
		Set<Dish> dishes = order.getDishes();
		List<Dish> dl = new ArrayList<Dish>();
		dl.addAll(dishes);
		Collections.sort(dl, new Comparator<Dish>() {

			@Override
			public int compare(Dish o1, Dish o2) {
				return o1.getNo() - o2.getNo();
			}
			
		});
		for (Dish dish : dl) {
			sb.append(" " + dish.getNo() + ",");
		}
		if (sb.length() > 0) {
			return sb.substring(0, sb.length() - 1);
		}
		
		return "";
	}
}
